<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Http\Forms\VideoForm;
use App\Modules\Common\Models\Video;

class VideoController extends ApiController
{
    public function index()
    {
        $data = Video::query()
            ->orderBy('created_at', 'desc')
            ->paginate(30);
        return view('video.index', compact('data'));
    }

    public function create()
    {
        $form = $this->form(VideoForm::class, [
            'method' => 'PUT',
            'url' => route('admin.video.store'),
        ]);
        return view('video.form', compact('form'));
    }

    public function store()
    {
        $form = $this->form(VideoForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        Video::query()
            ->create($data);
        return redirect()->route('admin.video.index');
    }

    public function edit($id)
    {
        $video = Video::query()->where('id', $id)->first();
        $video->video_key = $video->video;
        $form = $this->form(VideoForm::class, [
            'method' => 'POST',
            'url' => route('admin.video.update', ['id' => $id]),
            'model' => $video,
        ]);
        return view('video.form', compact('form'));
    }

    public function update($id)
    {
        $form = $this->form(VideoForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        Video::query()
            ->where('id', $id)
            ->update([
                "title" => $data['title'],
                "image" => $data['image'],
                "video" => $data['video'],
            ]);
        return redirect()->route('admin.video.index');
    }

    public function delete($id)
    {
        Video::query()->where('id', $id)->delete();
        return redirect()->route('admin.video.index');
    }
}
